import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:infinite_scroll_pagination/infinite_scroll_pagination.dart';
import 'package:sweetim/controller/friends_controller.dart';
import 'package:sweetim/model/friends.dart';
import 'package:sweetim/view/friends_details_view.dart';

class FriendsList extends StatelessWidget {
  const FriendsList({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    FriendsController friendsController = Get.put(FriendsController());
    return RefreshIndicator(
      onRefresh: () => Future.sync(
        () => friendsController.pagingController.refresh(),
      ),
      child: PagedListView<int, Friends>(
        pagingController: friendsController.pagingController,
        padding: const EdgeInsets.all(8.0),
        key: const PageStorageKey("friendList"),
        builderDelegate: PagedChildBuilderDelegate<Friends>(
          noItemsFoundIndicatorBuilder: (ctx) =>
              const Center(child: Text("空空如野 - -!")),
          itemBuilder: (context, item, index) =>
              FriendItem(friends: item, key: ValueKey(item.id)),
        ),
      ),
    );
  }
}

class FriendItem extends StatelessWidget {
  final Friends friends;

  const FriendItem({required this.friends, Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ListTile(
      contentPadding: const EdgeInsets.all(2.0),
      onTap: () => Get.to(FriendsDetails(friends: friends)),
      leading: CircleAvatar(
        backgroundColor: Colors.indigo[200],
        radius: 28,
        child: Text(
          friends.name?.substring(0, 1) ?? "",
          style: const TextStyle(
            fontWeight: FontWeight.bold,
          ),
        ),
      ),
      title: Text(friends.name ?? ""),
    );
  }
}
